/**
 * Created by Lossa on 2017/1/4.
 * 使用方法：
 * <play-sound url="http://www.example.com/url/sound/test.ogg" side="right"></play-sound>
 * url指向资源的url，side可选项
 */
angular.module('play-sound.directive', [])
    .directive('playSound', ['$state', '$timeout', '$interval',
        function ($state, $timeout, $interval) {
            return {
                restrict: 'E',
                replace: true,
                scope: {
                    url: '@url',//必填
                    side: '@side',//必填 左边还是右边
                },
                templateUrl: 'play-sound.html',
                link: function (scope, element, attr, controller) {
                    if (scope.side == 'right') {
                        element[0].className = 'play-sound play-sound-right'
                    }
                    var ctrl = undefined;//controller.为了协同其他audio工作，需要传递指令指令之间通信
                    scope.isLoading = true;//loading 标志位
                    scope.isNew = true;//isNew 标志位
                    scope.isError = false;//isError 标志位
                    var audio = element[0].getElementsByTagName('audio')[0];
                    var source = element[0].getElementsByTagName('source')[0];
                    var btn = element[0].getElementsByClassName('button')[0];
                    var stopInterval = undefined;
                    audio.addEventListener('canplaythrough', function (e) {
                        scope.dur = audio.duration;
                        scope.isLoading = false;
                        scope.isError = false;
                        if (scope.dur == 0) {
                            scope.dur = '?';
                        } else {
                            btn.style.width = parseInt(50 + (180 - 50) / 20 * scope.dur) + 'px';
                        }
                    }, false);


                    audio.addEventListener('ended', function () {
                        audio.pause();
                        audio.currentTime = 0;
                    }, false);


                    scope.$on('$ionicParentView.afterEnter', function (e, v) {
                        ctrl = e.targetScope;//获取controller scope的引用
                        ctrl.$on('play-sound:stop', function (e, v) {
                            if (v.who.$id != scope.$id) {
                                audio.pause();
                                audio.currentTime = 0;
                            }
                        });
                    });

                    scope.$on('$ionicParentView.beforeLeave', function (e, v) {
                        audio.pause();
                        soundListener();
                    });


                    scope.play = function () {
                        ctrl.$broadcast('play-sound:stop', {who: scope});
                        if (!audio.currentTime) {
                            scope.isNew = false;
                            audio.pause();
                            audio.currentTime = 0;
                            audio.play();

                            /**针对小米手机不preload的问题，采取的修正折中**/
                            stopInterval = $interval(function () {
                                console.log('interval doing:', audio.duration);
                                if (scope.dur != audio.duration && audio.duration > 0) {
                                    scope.dur = audio.duration;
                                    scope.isLoading = false;
                                    scope.isError = false;
                                    btn.style.width = parseInt(50 + (180 - 50) / 20 * scope.dur) + 'px';
                                }
                            }, 500);
                            $timeout(function () {
                                $interval.cancel(stopInterval);
                            }, 6000);

                        } else {
                            audio.pause();
                            audio.currentTime = 0;
                        }
                    };

                    scope.reload = function () {
                        audio.load();
                        scope.isLoading = true;
                    };
                }
            }
        }]);

angular.module('play-sound.filter', [])
    .filter('DurFilter', [function () {
        return function (time) {
            if (time) {
                console.log(time);
                return Math.round(time) + '\"';
            }
        };
    }])
    .filter('Trusted', ['$sce', function ($sce) {
        return function (url) {
            return $sce.trustAsResourceUrl(url);
        };
    }]);
;